import { AdminPermissionModel } from '~/server/models/admin_permission.model';

/**
 * @api {get} /admin/permission/list 获取管理员权限列表
 * @apiName 获取管理员权限列表
 * @apiGroup 后台管理员权限
 * @apiDescription 获取管理员权限列表
 *
 * @apiPermission admin
 *
 * @apiSampleRequest /admin/permission/list
 *
 * @apiHeader {String} Authorization 用户权限 Token
 *
 * @apiQuery {Number} currentPage 当前页码
 * @apiQuery {Number} pageSize 每页条数
 * @apiQuery {String} keyword 关键字搜索
 * @apiQuery {String} getAll 是否获取全部数据 'yes'
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccess {Object} data 数据
 * @apiSuccess {Array} data.list 权限列表
 * @apiSuccess {String} data.list._id 权限ID
 * @apiSuccess {String} data.list.name 权限名称
 * @apiSuccess {String} data.list.description 权限描述
 * @apiSuccess {String} data.list.createdAt 创建时间
 * @apiSuccess {String} data.list.updatedAt 更新时间
 * @apiSuccess {Number} data.total 总条数
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '获取成功',
 *   data: {
 *   list: [
 *     {
 *       "_id": "6839d56879cade8c6b9e367d",
 *       "name": "admin",
 *       "description": "超级管理员权限",
 *       "createdAt": "2025-05-30 23:57:26",
 *       "updatedAt": "2025-05-30 23:57:26",
 *       "__v": 0
 *   }],
 *   total: 5
 *   }
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, 'admin');
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	try {
		const query = getQuery(event);

		const getAll = query.getAll;
		const keyword = query.keyword ?? '';
		const pageSize = Number(query.pageSize);
		const currentPage = Number(query.currentPage);

		// 所有用户权限数量
		const total = await AdminPermissionModel.countDocuments();

		// 获取所有用户权限
		if (getAll === 'yes') {
			const list = await AdminPermissionModel.find({
				$or: [
					{ username: { $regex: keyword, $options: 'i' } },
					{ nickname: { $regex: keyword, $options: 'i' } },
				],
			});
			return {
				code: 1,
				message: '获取成功',
				data: {
					list,
					total,
				},
			};
		}

		// 判断参数是否为 number
		if (isNaN(currentPage) || isNaN(pageSize)) {
			return {
				code: 0,
				message: '参数错误',
			};
		}

		// 分页获取用户权限
		const list = await AdminPermissionModel.find({
			$or: [
				{ username: { $regex: keyword, $options: 'i' } },
				{ nickname: { $regex: keyword, $options: 'i' } },
			],
		})
			.skip((currentPage - 1) * pageSize)
			.limit(pageSize);

		return {
			code: 1,
			message: '获取成功',
			data: {
				list,
				total,
			},
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
